
package com.huyna.docbao;

import java.util.ArrayList;
import java.util.TooManyListenersException;

import com.huyna.docbao.Adapter.CategoryPaperAdapter;
import com.huyna.docbao.Adapter.ListItemAdapter;
import com.huyna.docbao.model.RowItem;

import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.res.Configuration;
import android.content.res.TypedArray;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.widget.DrawerLayout;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Gallery;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class MainActivity extends Activity{
    /* Declare controls */
//    private ImageView selectedImage;
    private Gallery     gallery;    //Gallery
    private ImageButton preButton;  //Button previous
    private ImageButton nexButton;  //Button next
    private ImageButton slideLeft;  //Button slide left
    private ImageButton slideRight; //
    private TextView    title;      //Title
    
    static String[]     menuTitles; //Array titles name
    TypedArray          menuIcons;  //Array icons
//    private CharSequence mDrawerTitle;  //Sequence title to draw
//    private CharSequence mTitle;        //Sequence title
    private DrawerLayout            mDrawerLayout;  //Drawer layout
    private ListView                mDrawerListLeft;    //Drawer list left side
    private ListView                mDrawerListRight;
    private ActionBarDrawerToggle   mDrawerToogle;  //Bar toggle
    private ActionBarDrawerToggle   mDrawerToggleRight;//
    /* Data adapter */
    private ArrayList<RowItem>  lstItem;    //List row item
    private ListItemAdapter     adapter;    //Adapter
    
    private boolean isNavOpened = false;    //Status navigation
    
    /* List image Id */
    public final Integer[] mImageId={
            R.drawable.gallery_photo_1,
            R.drawable.gallery_photo_2,
            R.drawable.gallery_photo_3,
            R.drawable.gallery_photo_4,
            R.drawable.gallery_photo_5,
            R.drawable.gallery_photo_6,
            R.drawable.gallery_photo_7,
            R.drawable.gallery_photo_8
        };
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        /* Find control from main activity */
        gallery = (Gallery)findViewById(R.id.Category);
//        selectedImage = (ImageView)findViewById(R.id.Image);
        preButton = (ImageButton)findViewById(R.id.previous);
        nexButton = (ImageButton)findViewById(R.id.next);
        mDrawerLayout = (DrawerLayout)findViewById(R.id.drawerLeft);
        mDrawerListLeft = (ListView)findViewById(R.id.listLeft);
        mDrawerListRight = (ListView)findViewById(R.id.listRight);//
        slideLeft = (ImageButton)findViewById(R.id.slideLeft);
        slideRight = (ImageButton)findViewById(R.id.slideRight);
        title = (TextView)findViewById(R.id.title);
        //
//        mTitle = mDrawerTitle = getTitle();
        /* Get data title and icon from resource */
        menuTitles = getResources().getStringArray(R.array.titles);
        menuIcons = getResources().obtainTypedArray(R.array.icons);
        /* Initialize list row item */
        lstItem = new ArrayList<RowItem>();
        /* Set data to list row item */
        for(int i=0;i<menuTitles.length;i++){
            RowItem item = new RowItem(menuIcons.getResourceId(i, -1), menuTitles[i]);
            lstItem.add(item);
        }
        /* Initialize adapter */
        adapter = new ListItemAdapter(getApplicationContext(), lstItem);
        /* Set to adapter to left side */
        mDrawerListLeft.setAdapter(adapter);
        /* Initial event of draw left list */
        mDrawerListLeft.setOnItemClickListener(new SlideItemClickListener());
        
        /* Set to adapter to right side */
        mDrawerListRight.setAdapter(adapter);//
        mDrawerListRight.setOnItemClickListener(new SlideRightItemClickListener());
        
        
        /* Enable button of ActionBar */
//        getActionBar().setDisplayHomeAsUpEnabled(true);
//        getActionBar().setHomeButtonEnabled(true);
        
        /* Initialize drawer toggle */
        mDrawerToogle = new ActionBarDrawerToggle(this, mDrawerLayout,
                R.drawable.ic_navigation_drawer_red, R.string.app_name, R.string.app_name){
            @Override
            /* When drawer toggle is closed */
            public void onDrawerClosed(View drawerView) {
//              getActionBar().setTitle(mTitle);
//              invalidateOptionsMenu();
              toogleNavigationPanel();
              /* Check if layout is opened on left side */
              if(mDrawerLayout.isDrawerOpen(Gravity.LEFT)){
                  //Do nothing
              }
            }
            
            @Override
            /* When drawer toggle is opened */
            public void onDrawerOpened(View drawerView) {
//              getActionBar().setTitle(mDrawerTitle);
//              invalidateOptionsMenu();
                toogleNavigationPanel();
            }
        };
        
        mDrawerToggleRight = new ActionBarDrawerToggle(this, mDrawerLayout,
                R.drawable.ic_navigation_drawer_red, R.string.app_name, R.string.app_name){

            @Override
            public void onDrawerClosed(View drawerView) {
                toogleNavigationPanel();
            }

            @Override
            public void onDrawerOpened(View drawerView) {
                toogleNavigationPanel();
            }
            
        };
        mDrawerLayout.setDrawerListener(mDrawerToogle);
        /* Initialize item is 0 and update screen */
//        if(savedInstanceState == null){
//            updateDisplay(0);
//        }
        /* Gallery */
        gallery.setAdapter(new CategoryPaperAdapter(this));
        /* Set space between two image */
        gallery.setSpacing(10);
        /* Initialize event when click on item of Gallery */
        gallery.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
                /* Show toast at index */
                Toast.makeText(MainActivity.this, "" + position, Toast.LENGTH_SHORT).show();
//                selectedImage.setImageResource(mImageId[position]);
                /* Initialize Fragment manager */
                FragmentManager fragmentManager = getFragmentManager();
                FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
                Fragment category = CategoryFragment.newInstance(position);
                fragmentTransaction.add(R.id.detailFrag, category);
                fragmentTransaction.commit();
            }
        });
        /* Initialize event click on buttons */
        preButton.setOnClickListener(onButtonClicked);  //Event button previous
        nexButton.setOnClickListener(onButtonClicked);  //Event button next
        onClickListenerForLeft();                       //Event button slide left
        onClickListenerForRight();
    }
    
    private void onClickListenerForRight() {
        slideRight.setOnClickListener(new OnClickListener(){

            @Override
            public void onClick(View v) {
                if(mDrawerLayout.isDrawerOpen(Gravity.RIGHT)){
                    mDrawerLayout.closeDrawer(Gravity.RIGHT);
                }
                else{
                    if(mDrawerLayout.isDrawerOpen(Gravity.LEFT)){
                        mDrawerLayout.closeDrawer(Gravity.LEFT);
                    }
                    mDrawerLayout.openDrawer(Gravity.RIGHT);
                }
            }
        });
    }

    /*
     * Event click on button slide left
     */
    private void onClickListenerForLeft(){
        /* Initialize event click on listener */
        slideLeft.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                /* Draw layout is opened on left side, close it*/
                if(mDrawerLayout.isDrawerOpen(Gravity.LEFT)){
                    mDrawerLayout.closeDrawer(Gravity.LEFT);
                }
                /* Otherwise, draw layout is opened */
                else{
                    if(mDrawerLayout.isDrawerOpen(Gravity.RIGHT)){
                        mDrawerLayout.closeDrawer(Gravity.RIGHT);
                    }
                    mDrawerLayout.openDrawer(Gravity.LEFT);
                }                
            }
        });
    }
    
    /*
     * Event on click on previous and next button
     */
    private OnClickListener onButtonClicked = new OnClickListener(){
        @Override
        public void onClick(View v) {
            int currItem = 0;   //Current item is selected
            switch(v.getId()){
                case R.id.previous:
                    /* Get position item is selected */
                    currItem = gallery.getSelectedItemPosition();
                    currItem -=1;
                    if(currItem < 0){
                        return;
                    }
                    else{
                        Toast.makeText(getApplicationContext(), "Image "+Integer.toString(currItem)+" is selected", Toast.LENGTH_SHORT).show();
                        gallery.setSelection(currItem);
                        gallery.onFling(null, null, (float)(currItem - 1), 0);
                    }
                    break;
                case R.id.next:
                    /* Get position item is selected */
                    currItem = gallery.getSelectedItemPosition();
                    currItem +=1;
                    if(currItem >= mImageId.length){
                        return;
                    }
                    else{
                        Toast.makeText(getApplicationContext(), "Image "+Integer.toString(currItem)+" is selected", Toast.LENGTH_SHORT).show();
                        gallery.setSelection(currItem);
                        gallery.onFling(null, null, (float)(currItem + 1), 0);
                    }
                    break;
                default:
                    break;
            }
        }        
    };
    
    @SuppressWarnings("deprecation")
    public void setNavigationOpen(final boolean isOpened){
        this.isNavOpened = isOpened;
        if(mDrawerLayout.isDrawerOpen(Gravity.LEFT)){
            slideLeft.setImageResource(R.drawable.ic_navigation_drawer_blue);
        }else{
//            slideLeft.setBackgroundDrawable(null);
            slideLeft.setImageResource(R.drawable.ic_navigation_drawer_red);
        }
        if(mDrawerLayout.isDrawerOpen(Gravity.RIGHT)){
            slideRight.setImageResource(R.drawable.ic_navigation_drawer_blue);
        }
        else{
            slideRight.setImageResource(R.drawable.ic_navigation_drawer_red);
        }
    }
    
    /*
     * Toggle navigation panel
     */
    private void toogleNavigationPanel(){
//        if(mDrawerLayout.isDrawerOpen(Gravity.LEFT)){
//            title.setText("Title");
//            //Do nothing
//        }
//        else{
//            //Do nothing
//        }
        setNavigationOpen(!isNavOpened);
    }
    
    /*
     * Class click listener on item
     */
    public class SlideItemClickListener implements OnItemClickListener {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            // TODO Auto-generated method stub
            updateDisplay(position);
        }
    }
    
    public class SlideRightItemClickListener implements OnItemClickListener{

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            // TODO Auto-generated method stub
            updateDisplay(position);
        }
    }
    /*
     * Update screen when item is selected
     */
    private void updateDisplay(int position){
        Fragment fragment = null;
        switch(position){
            case 0:
                fragment = new Item1Fragment();
                break;
            case 1:
                fragment = new Item2Fragment();
                break;
            default:
                break;
        }
        if(fragment != null){
            FragmentManager fragmentManager = getFragmentManager();
            fragmentManager.beginTransaction().replace(R.id.detailFrag, fragment).commit();
//            setTitle(menuTitles[position]);
            title.setText(menuTitles[position]);
            if(mDrawerLayout.isDrawerOpen(Gravity.LEFT)){
                mDrawerLayout.closeDrawer(mDrawerListLeft);
            }
            else if(mDrawerLayout.isDrawerOpen(Gravity.RIGHT)){
                mDrawerLayout.closeDrawer(mDrawerListRight);
            }
        }else{
            Log.e("MainActivity", "Error in creating fragment");
        }
    }
    
    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        mDrawerToogle.syncState();
    }
    
    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
//        mDrawerToogle.onConfigurationChanged(newConfig);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // TODO Auto-generated method stub
        return super.onCreateOptionsMenu(menu);
    }
    
    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        // TODO Auto-generated method stub
        return super.onPrepareOptionsMenu(menu);
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
//        if(mDrawerToogle.onOptionsItemSelected(item)){
//            return true;
//        }
        //Handle action bar event click
        return super.onOptionsItemSelected(item);
    }
    
    @Override
    public void setTitle(CharSequence title) {
//        mTitle = title;
//        getActionBar().setTitle(mTitle);
    }
}
